/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-03-22 19:15:21
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-03-22 20:41:34
 * @FilePath: /linux/test_3_22/blockqueue.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<queue>
using namespace std;
// pthread_mutex_t  lock = PTHREAD_MUTEX_INITIALIZER; 
// pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
template<class T>
class blockqueue
{
    static const int dt = 20;

    public:
    blockqueue(int max = dt):_max(max)
    {
        pthread_mutex_init(&lock,nullptr);
        pthread_cond_init(&c_cond,nullptr);
        pthread_cond_init(&p_cond,nullptr);

    }
    void * push(const T& t)
    {
        pthread_mutex_lock(&lock);
        if(_q.size()==_max)
        {
        pthread_cond_wait(&p_cond,&lock);
        }
        _q.push(t);
        if(_q.size()>_max/2)
        pthread_cond_signal(&c_cond);
        pthread_mutex_unlock(&lock);

    }
    T pop()
    {
        pthread_mutex_lock(&lock);
        if(_q.size()==0)
        {
        pthread_cond_wait(&c_cond,&lock);
        }
        T ret = _q.front();
        _q.pop();
        pthread_cond_signal(&p_cond);
        pthread_mutex_unlock(&lock);
        return ret;
    }
    ~blockqueue()
    {
        pthread_mutex_destroy(&lock);
        pthread_cond_destroy(&c_cond);
        pthread_cond_destroy(&p_cond);

    }
    private:
       std::queue<T> _q;
        pthread_mutex_t lock;
        pthread_cond_t c_cond;
        pthread_cond_t p_cond;

      int _max;   
};